package com.example.myxmpp.activity;

import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;


import androidx.appcompat.app.AppCompatActivity;

import com.example.myxmpp.R;
import com.example.myxmpp.dbhelper.SmsOpenHelper;
import com.example.myxmpp.provider.SmsProvider;
import com.example.myxmpp.service.IMService;
import com.example.myxmpp.utils.ThreadUtils;

import org.apache.commons.lang3.StringUtils;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.chat2.Chat;
import org.jivesoftware.smack.chat2.ChatManager;
import org.jivesoftware.smack.chat2.IncomingChatMessageListener;
import org.jivesoftware.smack.packet.Message;
import org.jxmpp.jid.EntityBareJid;
import org.jxmpp.jid.impl.JidCreate;
import org.jxmpp.stringprep.XmppStringprepException;

import java.io.IOException;
import java.nio.CharBuffer;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ChatActivity extends AppCompatActivity {

    public static final String CLICKACCOUNT = "clickAccount";
    public static final String CLICKNICKNAME = "clickNickName";
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.listView)
    ListView listView;
    @BindView(R.id.et_body)
    EditText etBody;
    @BindView(R.id.btn_send)
    Button btnSend;

    private String mClickAccount;
    private String mClickNickName;
    private CursorAdapter adapter;

    //private Chat chat;

    private Map<String,Chat> mChatMap = new HashMap<>();
    private IMService imService;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        ButterKnife.bind(this);

        init();
        initView();
        initData();
        initlistener();

    }

    private void init() {
        registerContentObserver();
        //绑定服务
        Intent service = new Intent(ChatActivity.this,IMService.class);
        bindService(service,myServiceConnection,BIND_AUTO_CREATE);

        mClickAccount = getIntent().getStringExtra(ChatActivity.CLICKACCOUNT);
        mClickNickName = getIntent().getStringExtra(ChatActivity.CLICKNICKNAME);



    }

    private void initView() {
        //设置Title
        title.setText("与"+mClickNickName+"聊天中");
    }

    private void initData() {

        setAdapterOrNotify();


    }

    private void setAdapterOrNotify() {
        //1.首先判是否存存adapter
        if (adapter  != null){
            //刷新
            Cursor cursor = adapter.getCursor();
            cursor.requery();

            listView.setSelection(cursor.getCount()-1);//显示最后一行，滚动模式

            Log.i("s","setAdapterOrNotify adapter != null 刷新");
            return;
        }
        ThreadUtils.runInThread(new Runnable() {
            @Override
            public void run() {
              final Cursor c = getContentResolver().query(SmsProvider.URI_SMS,null,
                      "(from_account = ? and to_account=?)or(from_account = ? and to_account = ? )",//where条件
                      new String[]{IMService.mCurAccount,mClickAccount,mClickAccount,IMService.mCurAccount},
                      SmsOpenHelper.SmsTable.TIME +" ASC"); //时间升序排序

                if(c.getCount()<1){//如果没有数据直接返回
                    Log.i("c","c.getCount<1如果没有数据直接返回");
                    return;
                }
                ThreadUtils.runInUIThread(new Runnable() {



                    @Override
                    public void run() {
                        adapter = new CursorAdapter(ChatActivity.this,c) {
                            private static final int RECEIVE = 1;

                            private static final int SEND = 0;

                            /* @Override
                            public View newView(Context context, Cursor cursor, ViewGroup parent) {
                                //convertView == null 是会调用，返回根布局
                                TextView tv = new TextView(context);
                                return tv;
                            }

                            @Override
                            public void bindView(View view, Context context, Cursor cursor) {
                                TextView tv = (TextView) view;
                                //具体设置数据
                                String body = cursor.getString(cursor.getColumnIndex(SmsOpenHelper.SmsTable.BODY));
                                tv.setText(body);
                            }
                            */

                            @Override
                            public int getItemViewType(int position) {
                                c.moveToPosition(position);
                                //取出消息的创建者
                                String fromAccount = c.getString(c.getColumnIndex(SmsOpenHelper.SmsTable.FROM_ACCOUNT));
                                if (!IMService.mCurAccount.equals(fromAccount)){
                                    //接收者
                                    return RECEIVE;
                                }else{
                                    //发送者

                                    return SEND;
                                }
                               // return super.getItemViewType(position);//0--1
                            }

                            @Override
                            public int getViewTypeCount() {
                                return super.getViewTypeCount()+1;//2
                            }

                            @Override
                            public View getView(int position, View convertView, ViewGroup parent) {
                                ViewHolder holder;
                                if (getItemViewType(position)==RECEIVE){

                                    if (convertView == null){
                                        convertView = View.inflate(ChatActivity.this,R.layout.item_chat_receive,null);
                                        holder = new ViewHolder();
                                        convertView.setTag(holder);

                                        //holder赋值
                                        holder.time = convertView.findViewById(R.id.time);
                                        holder.body = convertView.findViewById(R.id.content);
                                        holder.head = convertView.findViewById(R.id.head);
                                    }else{
                                        holder = (ViewHolder) convertView.getTag();
                                    }
                                }else{

                                    if (convertView == null){
                                        convertView = View.inflate(ChatActivity.this,R.layout.item_chat_send,null);
                                        holder = new ViewHolder();
                                        convertView.setTag(holder);

                                        //holder赋值
                                        holder.time = convertView.findViewById(R.id.time);
                                        holder.body = convertView.findViewById(R.id.content);
                                        holder.head = convertView.findViewById(R.id.head);
                                    }else{
                                        holder = (ViewHolder) convertView.getTag();
                                    }

                                }

                                c.moveToPosition(position);
                                String time = c.getString(c.getColumnIndex(SmsOpenHelper.SmsTable.TIME));
                                String body = c.getString(c.getColumnIndex(SmsOpenHelper.SmsTable.BODY));

                                String formatTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(Long.parseLong(time)));

                                holder.time.setText(formatTime);
                                holder.body.setText(body);

                                return super.getView(position, convertView, parent);
                            }

                            @Override
                            public View newView(Context context, Cursor cursor, ViewGroup parent) {
                                return null;
                            }

                            @Override
                            public void bindView(View view, Context context, Cursor cursor) {

                            }

                            class ViewHolder{
                                TextView body;
                                TextView time;
                                ImageView head;
                            }
                        };
                        listView.setAdapter(adapter);
                        //滚动到最后一行
                        listView.setSelection(adapter.getCount()-1);
                    }
                });

            }
        });
    }

    private void initlistener() {

    }

    @OnClick(R.id.btn_send)
    public void send(View v) {
       final String body = etBody.getText().toString();
       // Toast.makeText(getApplicationContext(),body,Toast.LENGTH_SHORT).show();

        ThreadUtils.runInThread(new Runnable() {


            private Message msg;

            @Override
            public void run() {
              try {
                  EntityBareJid jid = JidCreate.entityBareFrom(mClickAccount);
                  msg = new Message();
                  Log.i("d", "++++++++++++" + IMService.mCurAccount.toString() + "+++++++");
                  msg.setFrom(JidCreate.from(IMService.mCurAccount));//我的登陆账号　
                  msg.setTo(jid);
                  msg.setBody(body);
                  msg.setType(Message.Type.chat);
              }catch (Exception e){
                  e.printStackTrace();
              }

                //发送消息
                sendMessage(msg);


                //清空输入框
                ThreadUtils.runInUIThread(new Runnable() {
                    @Override
                    public void run() {
                        etBody.setText("");
                    }
                });
            }
        });

    }

    private void sendMessage(Message msg) {
        //发送消息

        EntityBareJid jid = null; //读取的账号
         Chat chat = null;
        try {
            jid = JidCreate.entityBareFrom(msg.getTo());

            String toAccount = msg.getTo().toString();
            if (mChatMap.containsKey(toAccount)){
                chat = mChatMap.get(toAccount);
            }else{
                //没有
                chat = IMService.chatManager.chatWith(jid);
                mChatMap.put(toAccount,chat);
            }

            String m = StringUtils.substringBefore(msg.getTo().toString(),"/");//分割取前段
            saveMessage2(m,msg);

            chat.send(msg);

        } catch (XmppStringprepException e) {
            e.printStackTrace();
        } catch (SmackException.NotConnectedException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private  void saveMessage2(String sessionAccount, Message msg){
        ContentValues values = new ContentValues();

        values.put(SmsOpenHelper.SmsTable.FROM_ACCOUNT,msg.getFrom().toString());
        values.put(SmsOpenHelper.SmsTable.TO_ACCOUNT,msg.getTo().toString());
        values.put(SmsOpenHelper.SmsTable.BODY,msg.getBody());
        values.put(SmsOpenHelper.SmsTable.STATUS,"offline");
        values.put(SmsOpenHelper.SmsTable.TYPE,msg.getType().name());
        values.put(SmsOpenHelper.SmsTable.TIME,System.currentTimeMillis());
        values.put(SmsOpenHelper.SmsTable.SESSION_ACCOUNT, sessionAccount);
        getContentResolver().insert(SmsProvider.URI_SMS,values);
    }

    @Override
    protected void onDestroy() {
        unRegisterContentObserver();
        //chatManager.removeIncomingListener();

        //解绑服务
        if (myServiceConnection !=null){
            unbindService(myServiceConnection);
        }
     super.onDestroy();
    }

    //使用contentObserver
    MyContentObserver myContentObserver = new MyContentObserver(new Handler());
    //注册监听
    public void registerContentObserver(){
        getContentResolver().registerContentObserver(SmsProvider.URI_SMS,true,myContentObserver);
    }
    //反注册监听
    public  void unRegisterContentObserver(){
        getContentResolver().unregisterContentObserver(myContentObserver);
    }



    class MyContentObserver extends ContentObserver{

        /**
         * Creates a content observer.
         *
         * @param handler The handler to run {@link #onChange} on, or null if none.
         */
        public MyContentObserver(Handler handler) {
            super(handler);
        }

        /**
         * 接收到数据记录的改变
         * @param selfChange
         * @param uri
         */
        @Override
        public void onChange(boolean selfChange, Uri uri) {
            //设置adapter或者notifyadapter
            setAdapterOrNotify();
            super.onChange(selfChange, uri);
        }
    }

    MyServiceConnection myServiceConnection = new MyServiceConnection();
    class MyServiceConnection implements ServiceConnection{

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.i("tt","=======onServiceConnected=======");
            IMService.MyBinder binder = (IMService.MyBinder) service;
            imService = binder.getService();

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.i("tt","=======onServiceDisconnected=======");
        }
    }
}
